﻿using System;
using System.Collections.Generic;

namespace xshare
{


    public class Pool<T> where T : class
    {

        Queue<T> _pool = new Queue<T>();
        int _maxCount;
        int _createCount;

        Func<object, T> _onCreate;
        Action<object, T> _onRecycle;


        public Pool() 
            : this(5, null, null)
        {
        }

        public Pool(Func<object, T> onCreate, Action<object, T> onRecycle) 
            : this(5, onCreate, onRecycle)
        {
        }

        public Pool(int max, Func<object, T> onCreateFunc, Action<object, T> onRecycleFunc)
        {
            _maxCount = max;
            _onCreate = onCreateFunc;
            _onRecycle = onRecycleFunc;
        }

        public T Obtain()
        {
            if (_pool.Count > 0)
                return _pool.Dequeue();

            _createCount++;
            if (_createCount > _maxCount)
                Log.w($"Pool: create too many instance: {_createCount}");

            if (null == _onCreate)
                return default(T);

            return _onCreate(this);
        }

        public bool Recycle(T t)
        {
            if (_pool.Count > _maxCount)
                return false;

            if (null != _onRecycle)
                _onRecycle(this, t);

            _pool.Enqueue(t);
            return true;
        }


        public bool Contains(T t)
        {
            return _pool.Contains(t);
        }

    } //end of class


}